// delay for given number of microseconds (use 22-65535) or milliseconds (1-65535) using timer 2
// delayT2_us minimum is 22 us
// (C) Copyright 2009, 2010 Communications Programming, Inc.

#include "userLib.h"
#include "timers.h"

void delayT2_init()					// init timer for first use
{
	T2CON = T2CON_VAL;				// timer on, set prescale 
}

void delayT2_us( uint16 us )		// delay a given number of microseconds
{
	WriteTimer2(0);
	us *= timer_ticks_per_microsec;
	us = us >> 1;
	if( us >= DELAY_OVERHEAD_TICKS )
	{
		us -= DELAY_OVERHEAD_TICKS;
		while( us > 250 )
		{
			while( ReadTimer2() < 249 )	// chunks < 256 for 8-bit timer
			{}
			us -= 250;	
			WriteTimer2(0);
		}	
		while( ReadTimer2() < us )
		{}
	}	
}

void delayT2_ms( uint16 ms )		// delay a given number of milliseconds (1-65535)
{
	while( ms-- )
	{
		delayT2_us(1000);	
	}
}

